//
//  XMPPManager.m
//  XMPPManager
//
//  Created by cocoajin on 14-4-17.
//  Copyright (c) 2014年 com.9ask. All rights reserved.
//

#import "XMPPManager.h"
#import "OpenUDID.h"
#import "DigitalConfig.h"


//#import <RobotSDK/RobotSDK.h>
static XMPPManager *manager = nil;

@interface XMPPManager ()
{
    NSString *theUserName;
    NSString *thePasswrod;
}

@end

@implementation XMPPManager

#pragma mark public method
+ (XMPPManager*)manager
{
    if (manager == nil)
    {
        @synchronized(self)
        {
            if (manager == nil)
            {
                manager = [[super alloc] init];
            }
        }
    }
    return manager;
}


- (void)setUserName:(NSString *)userName password:(NSString *)pwd
{
    theUserName = userName;
    thePasswrod = pwd;
}

- (void)setUpStream
{
    self.xmppStream = [[XMPPStream alloc]init];
    if (self.theHostIP==nil || thePasswrod==nil || theUserName==nil)
    {
        //        NSLog(@" -- 服务器连接错误111111：ip、用户名、密码 不能为空。");
    }
    XMPPJID *jid = [XMPPJID jidWithUser:theUserName domain:[DigitalConfig shareConfig].domain resource:[DigitalConfig shareConfig].groupId];
    [_xmppStream setMyJID:jid];
    [_xmppStream setHostName:self.theHostIP];
    [self.xmppStream setHostPort:[DigitalConfig shareConfig].servePort]; //设置xmpp端口，默认5222
    
    [_xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
    [self.xmppStream setKeepAliveInterval:30]; //心跳包时间
    
}

- (BOOL)connectServer
{
    [self setUpStream];
    
    if (![_xmppStream isDisconnected]) {
        return YES;
    }
    

    NSError *connectError = nil;
    if (![_xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&connectError]) {
//        NSLog(@" -- 服务器连接错误：%@",connectError);
        
        return NO;
    }
    return YES;
}

- (void)disConnect
{
    [self goOffLine];
    [_xmppStream disconnect];
}

- (void)goOnLine
{
    XMPPPresence *presence = [XMPPPresence presence];
    NSString *domain =[_xmppStream.myJID domain];
//    NSLog(@"domain:%@",domain);
    //Google set their presence priority to 24, so we do the same to be compatible.
    
    if([domain isEqualToString:@"gmail.com"]
       || [domain isEqualToString:@"gtalk.com"]
       || [domain isEqualToString:@"talk.google.com"])
    {
        NSXMLElement *priority = [NSXMLElement elementWithName:@"priority" stringValue:@"24"];
        [presence addChild:priority];
    }
    [_xmppStream sendElement:presence];
    
    if ([self.delegate respondsToSelector:@selector(userLoginSuccess:)]) {
        [self.delegate userLoginSuccess:_xmppStream.myJID];
    }
}

- (void)goOffLine
{
    XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
    
    [_xmppStream sendElement:presence];
}
- (void)setPingEvent {
    NSDictionary *bodyDic = @{
        @"event":@"ping",
        @"uuid":[DigitalConfig shareConfig].uuid, // 会话id
    };
    [self sendXmppMessage:bodyDic];

    [self performSelector:@selector(setPingEvent) withObject:nil afterDelay:5];
}
/// MARK: ============= start事件，由客户端主动发起 ================
- (void)toStartMessage
{
    NSDictionary *bodyDic = @{
        @"event":@"start",
        @"uuid":[DigitalConfig shareConfig].uuid, // 会话id
        @"variable":@{
            @"robotCode":[DigitalConfig shareConfig].robotCode,
            @"terminal":@"app",
            @"mediaMode":@"web_rtc",
            @"interactMode":@"live", // 老韩提供
            @"robotMode":[DigitalConfig shareConfig].robotMode,
            @"openAsr":[DigitalConfig shareConfig].openAsr,
            @"device" : [DigitalConfig shareConfig].device,
            @"groupId" : [DigitalConfig shareConfig].groupId
        }
    };
    [self sendXmppMessage:bodyDic];

        
}
/// MARK: ============= 发送sdp给服务端 ================
- (void)offerSdp:(NSString *)sdp {
    
    NSDictionary *bodyDic = @{
        @"event":@"transfer",
        @"uuid":[DigitalConfig shareConfig].uuid,
        @"variable":@{
            @"method":@"AnswerSession",
            @"params":@{
                @"sdp":@{
                    @"type":@"answer",
                    @"sdp":sdp
                },
                @"sessionId":[DigitalConfig shareConfig].uuid // 同 uuid
            },
           @"id":@1
        }
    };
    [self sendXmppMessage:bodyDic];
}
/// MARK: 打洞数据通知客户端
- (void)candidateEvent:(NSDictionary *)candidateDic {
    NSDictionary *dic = @{
        @"event":@"transfer",
        @"uuid":[DigitalConfig shareConfig].uuid,
        @"variable":@{
            @"method":@"AddSessionCandidate",
            @"params":@{
                @"sessionId":[DigitalConfig shareConfig].uuid,
                @"candidate": @{
                        @"candidate":candidateDic[@"candidate"]?:@"",
                        @"sdpMid":candidateDic[@"sdpMid"]?:@"",
                        @"sdpMLineIndex":candidateDic[@"sdpMLineIndex"],
                        @"serverUrl":candidateDic[@"serverUrl"]?:@"",
                        @"adapterType":@""
                    }
            },
            @"sessionId":[DigitalConfig shareConfig].uuid,
            @"id":@"1"
        }
    };
    [self sendXmppMessage:dic];
    
}
- (void)clientReadyEvent {
    NSDictionary *dic = @{
        @"event":@"clientReady",
        @"uuid":[DigitalConfig shareConfig].uuid
    };
    [self sendXmppMessage:dic];

}
/// 给中控发送文本（驱动模式robotMode为空）
/// @param content 文本内容
- (void)commandEvent:(NSString *)content {
    NSDictionary *dic = @{
        @"event":@"command",
        @"uuid":[DigitalConfig shareConfig].uuid,
        @"content":content
    }        ;
    
    [self sendXmppMessage:dic];
}
/// 对话模式用answer事件
- (void)answerCommandEvent:(NSString *)content isAudio:(BOOL)isAudio {
    /// 如果是语音
    NSDictionary *dic = nil;
    if (isAudio) {
        dic = @{
            @"event":@"command",
            @"uuid":[DigitalConfig shareConfig].uuid,
            @"content":@"",
            @"variable":@{
                @"wavPath":content
            }
        };
    }else {
        dic = @{
            @"event":@"command",
            @"uuid":[DigitalConfig shareConfig].uuid,
            @"content":content,
            @"variable":@{
                @"wavPath":@""
            }
        };
    }
    
    [self sendXmppMessage:dic];
}
- (void)changeAsrEvent:(BOOL)isOpen {
    NSDictionary *dic = @{
        @"event":isOpen ? @"openAsr" : @"closeAsr",
        @"uuid":[DigitalConfig shareConfig].uuid,
    };
    [self sendXmppMessage:dic];

}

- (void)sendXmppMessage:(NSDictionary *)bodydic {
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:bodydic options:NSJSONWritingPrettyPrinted error:nil];
    if (bodyData!=nil)
    {
        NSString *body_str = [[NSString alloc] initWithData:bodyData encoding:NSUTF8StringEncoding];
        NSLog(@"bodydic ===== %@", body_str);
        NSString *toStr = [DigitalConfig shareConfig].userJID;
        NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
        [body setStringValue:body_str];
        NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
        [message addAttributeWithName:@"type" stringValue:@"chat"];
        [message addAttributeWithName:@"to" stringValue:toStr];
        [message addChild:body];
        
        NSLog(@"发送消息给XMPP:%@",message);
        
        [[XMPPManager manager].xmppStream sendElement:message];
    }
}


#pragma mark XMPPStream Delegate

//socket连接建立成功
- (void)xmppStream:(XMPPStream *)sender socketDidConnect:(RCDAsyncSocket *)socket
{
    NSLog(@"socket连接建立成功");
}

//连接成功到服务器
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
    NSError *authError = nil;
    if (![_xmppStream authenticateWithPassword:thePasswrod error:&authError]) {
        if (authError) {
            NSLog(@" -- 服务器密码难证错误：%@",authError);
                if (self.delegate && [self.delegate respondsToSelector:@selector(onError:)]) {
                    [self.delegate onError:authError];
                }
        }
    }
}

//登录验证成功
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
    //上线--更改状态

    [self goOnLine];
    
}

//验证登录失败
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
    NSLog(@" -- 验证登录错误：%@",error);
//    if (self.delegate && [self.delegate respondsToSelector:@selector(onError:)]) {
//        [self.delegate onError:error];
//    }
}

//收到信息
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
    
    /*
    if ([message isChatMessageWithBody])
    {
        
        NSString *body = [[message elementForName:@"body"] stringValue];
        NSString *displayName = [[message from] user];
        
        if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:displayName
                                                                message:body
                                                               delegate:nil
                                                      cancelButtonTitle:@"Ok"
                                                      otherButtonTitles:nil];
            [alertView show];
        }
        else
        {
            // We are not active, so use a local notification instead
            UILocalNotification *localNotification = [[UILocalNotification alloc] init];
            localNotification.alertAction = @"Ok";
            localNotification.alertBody = [NSString stringWithFormat:@"From: %@\n\n%@",displayName,body];
            
            [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
        }
    }
     
     */
    
    if ([self.delegate respondsToSelector:@selector(didReceiveMessage:)]) {
        [self.delegate didReceiveMessage:message];
    }
    
    

}

/// 好友在线状态
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
{
    //取得好友状态
    NSString *presenceType = [presence type]; //online/offline
    NSString *userId = [[sender myJID] user];
    NSString *presenceFromUser = [[presence from] user];
    //NSLog(@" -- 用户状态：%@ %@",presenceFromUser,presenceType);
    
    if (![presenceFromUser isEqualToString:userId]) {
        
        //在线状态
        if ([presenceType isEqualToString:@"available"]) {
            
            if ([self.delegate respondsToSelector:@selector(newUserOnline:)]) {
                [self.delegate newUserOnline:presence];
            }
        }
        else if ([presenceType isEqualToString:@"unavailable"]) {
            
            if ([self.delegate respondsToSelector:@selector(hasUserOffline:)]) {
                [self.delegate hasUserOffline:presence];
            }
            
        }
        
        
    }
}

//收到连接错误
- (void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error
{
    NSLog(@" ** 收到 Stream 错误 %@",error);
//    if (self.delegate && [self.delegate respondsToSelector:@selector(onError:)]) {
//        [self.delegate onError:error];
//    }
}

//断开连接发生错误
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
    NSLog(@" ** 断开服务器连接 错误 %@",error.localizedDescription);
    if (self.delegate && [self.delegate respondsToSelector:@selector(onError:)]) {
        [self.delegate onError:error];
    }

}


@end
